<?php namespace Admin\Controller;
//分类控制器
class CateController extends CommonController
{
    private $model;

    public function __auto()
    {
        $this->model=new \Common\Model\Cate;
    }

    //显示分类列表首页
    public function index()
    {
        //如果没有分类，跳到添加页面
        $data =$this->model->join('type','typeid','=','type_typeid')->get();
        if (!$data) {
            View::success('请先去添加类型', U('add'));
        }
        $data=Data::tree($data,'cname');
        View::with('data', $data);
        View::make();
    }
    //添加顶级分类
    public function add(){
        if(IS_POST){
            if($this->model->store()){
                View::success("添加成功",U('index'));
            }
            View::error($this->model->getError());
        }
        $typeModel=new \Common\Model\Type;
        $typeData=$typeModel->get();
        View::with('typeData',$typeData);
        View::make();
    }
    //添加子分类控制器
    public function addSon(){
        if(IS_POST){
            if($this->model->store()){
                View::success('子类添加成功',U('index'));
            }
            View::error($this->model->getError());
        }
        $type=new \Common\Model\Type;
        $typeData=$type->get();
        $cid=Q('get.cid',0,'intval');
        $cateData=$this->model->join('type','typeid','=','type_typeid')->where("cid={$cid}")->find();
        View::with('typeData',$typeData);
        View::with('data',$cateData);
        View::make();
    }
    //编辑分类
    public function edit(){
        if(IS_POST){
            $cid=Q('post.cid',0,'intval');
//            $typeid=$this->model->where("cid={$cid}")->pluck('type_typeid');
            $this->model->changeSon($cid);
            if($this->model->edit()){
                View::success("修改成功",U('index'));
            }
            View::error($this->model->getError());
        }
        //获得旧数据
        $type=new \Common\Model\Type;
        $typeData=$type->get();
        //获取typeid用于更改子集的typeid
        $cid=Q('get.cid',0,'intval');
        $oldData=$this->model->join('type','typeid','=','type_typeid')->where("cid={$cid}")->find();
        //获得处理自己和自己的子集
        $cateData=Data::tree($this->model->getNoMy($cid),'cname');
//        P($cateData);
        //分配type表数据 获取类型
        View::with('typeData',$typeData);
        //分配分类子父集数据
        View::with('cateData',$cateData);
        View::with('oldData',$oldData);
        View::make();
    }
    public function del(){
        $cid=Q('get.cid',0,'intval');
        $cids=$this->model->getSon($this->model->get(),$cid);
        $cids[]=$cid;
        foreach ($cids as $c){
            $this->model->where("cid={$c}")->delete();
        }
        View::success("删除成功",U('index'));
    }
}